import os
import yaml
from datetime import timedelta

# 获取当前文件所在目录的路径
CONFIG_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(CONFIG_DIR)

def load_config():
    """加载配置文件"""
    try:
        config_path = os.path.join(CONFIG_DIR, 'config.yml')
        with open(config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"Error loading config file: {e}")
        raise

class Config:
    # 加载 YAML 配置
    _config = load_config()
    
    # 基础配置
    SECRET_KEY = _config.get('app', {}).get('secret_key', 'dev')
    UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, _config.get('app', {}).get('upload_folder', 'uploads'))
    MAX_CONTENT_LENGTH = _config.get('app', {}).get('max_content_length', 16777216)  # 16MB
    
    # Ollama 配置
    OLLAMA = _config.get('ollama', {})
    
    # 数据库配置
    db_config = _config.get('database', {})
    SQLALCHEMY_DATABASE_URI = f"postgresql://{db_config.get('user')}:{db_config.get('password')}@{db_config.get('host')}:{db_config.get('port')}/{db_config.get('name')}"
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    
    # 向量搜索配置
    VECTOR_SEARCH = _config.get('vector_search', {
        'similarity_threshold': 0.5,
        'top_k_results': 5,
        'embedding_dimension': 1024
    })
    
    # 文档处理配置
    ALLOWED_EXTENSIONS = set(_config.get('document', {}).get('allowed_extensions', []))
    CHUNK_SIZES = _config.get('document', {}).get('chunk_sizes', {
        'char': 500,
        'word': 100,
        'sentence': 5
    })
    
    # 日志配置
    LOG_DIR = os.path.join(PROJECT_ROOT, _config.get('logging', {}).get('dir', 'logs'))
    LOGGING = _config.get('logging', {
        'level': 'INFO',
        'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        'max_size': 10485760,  # 10MB
        'backup_count': 10
    })
    
    def __init__(self):
        # 确保必要的目录存在
        os.makedirs(self.UPLOAD_FOLDER, exist_ok=True)
        os.makedirs(self.LOG_DIR, exist_ok=True)

    @staticmethod
    def init_app(app):
        """初始化应用配置"""
        # 验证必要的配置
        if not app.config['OLLAMA'].get('base_url'):
            app.logger.warning("OLLAMA base_url not configured, using default: http://localhost:11434")
            app.config['OLLAMA']['base_url'] = 'http://localhost:11434'
            
        if not app.config['OLLAMA'].get('embedding_model'):
            app.logger.warning("OLLAMA embedding_model not configured, using default: bge-large")
            app.config['OLLAMA']['embedding_model'] = 'bge-large'

class DevelopmentConfig(Config):
    DEBUG = True

    @classmethod
    def init_app(cls, app):
        Config.init_app(app)
        # 打印关键配置
        app.logger.info(f"Using Ollama config: {app.config.get('OLLAMA')}")

class ProductionConfig(Config):
    DEBUG = False

class TestingConfig(Config):
    TESTING = True
    # 测试环境使用相同的数据库配置，但使用不同的数据库名称
    db_config = Config._config.get('database', {})
    SQLALCHEMY_DATABASE_URI = f"postgresql://{db_config.get('user')}:{db_config.get('password')}@{db_config.get('host')}:{db_config.get('port')}/test_{db_config.get('name')}"

# 配置映射
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
} 